package com.trytech.mongoocrawler.client.transport;

import com.trytech.mongoocrawler.client.common.http.CrawlerHttpRequest;
import com.trytech.mongoocrawler.client.common.http.WebResult;
import com.trytech.mongoocrawler.client.common.queue.DisruptorContext;
import com.trytech.mongoocrawler.client.common.queue.WebFetcherEventProducer;
import com.trytech.mongoocrawler.client.transport.http.HttpConnector;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * Created by hp on 2017-1-24.
 */
public class TaskWorker implements Runnable {
    private int REQUESTS_MAX_COUNT=10;//最多尝试请求10次，否则丢弃请求
    private CrawlerHttpRequest request;
    private DisruptorContext disruptorContext;
    private WebFetcherEventProducer webFetcherEventProducer;

    public TaskWorker(CrawlerHttpRequest request, DisruptorContext disruptorContext){
        this.request = request;
        this.disruptorContext = disruptorContext;
        this.webFetcherEventProducer = new WebFetcherEventProducer(disruptorContext.getWebResultRingBuffer());
    }

    public DisruptorContext getDisruptorContext(){
        return disruptorContext;
    }
    @Override
    public void run() {
        try {
            for(int i=0;i<=REQUESTS_MAX_COUNT;i++){
                WebResult<String> result = HttpConnector.sendRequest(request);
                result.setUrl(request.getUrl().toString());
                WebResult.StatusCode statuscode = result.getStatuscode();
                if(statuscode == WebResult.StatusCode.SUCCESS){
                    //将网页发送到disruptor中
                    webFetcherEventProducer.sendData(result);
                    break;
                }
                if(i==REQUESTS_MAX_COUNT){
                    //丢弃请求并打印日志

                }
            }

        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
